<?php

// 公共助手函数

use Symfony\Component\VarExporter\VarExporter;
use think\Cache;
use think\Db;
use think\Env;
use think\exception\HttpResponseException;
use think\Response;

function saveBase64($base64_img)
{
    //目录的upload文件夹下
    $up_dir = ROOT_PATH . "public/uploads/base64img/";  //创建目录
    if (!file_exists($up_dir)) {
        mkdir($up_dir, 0777, true);
    }
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
        $type = $result[2];
        if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
            $name = \fast\Random::alnum(32);
            $new_file = $up_dir . $name . '.' . $type;
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))) {
                return "/uploads/base64img/" . $name . '.' . $type;
            }
        }
    }
    return false;
}
function img_base64($path)
{
    //对path进行判断，如果是本地文件就二进制读取并base64编码，如果是url,则返回
    $img_data = "";
    if (substr($path, 0, strlen("http")) === "http") {
        $img_data = $path;
    } else {
        if ($fp = fopen($path, "rb", 0)) {
            $binary = fread($fp, filesize($path)); // 文件读取
            fclose($fp);
            $img_data = base64_encode($binary); // 转码
        } else {
            printf("%s 图片不存在", $path);
        }
    }
    return $img_data;
}
if (!function_exists('dd')) {

    function dd($data)
    {
        dump($data);
        die();
    }
}
/*替换，姓名字符串*/
function substrCut($userName)
{
    // dd(preg_replace('/(?<=^.{1})./u', '*', '张在张在张在张在张在'));
    $strlen = mb_strlen($userName, 'utf-8');
    $firstStr = mb_substr($userName, 0, 1, 'utf-8');
    $lastStr = mb_substr($userName, -1, 1, 'utf-8');
    if ($strlen == 2) {
        $resultName = $firstStr . str_repeat('*', mb_strlen($userName, 'utf-8') - 1);
    }
    if ($strlen > 2) {
        $resultName = $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
    }
    if ($strlen < 2) {
        $resultName = $userName;
    }
    return $resultName;
}
if (!function_exists('sn')) {
    /**
     * 生成订单号
     */
    function sn($table, $field, $prefix = '', $rand_suffix_length = 4, $pool = [])
    {
        $suffix = '';
        for ($i = 0; $i < $rand_suffix_length; $i++) {
            if (empty($pool)) {
                $suffix .= rand(0, 9);
            } else {
                $suffix .= $pool[array_rand($pool)];
            }
        }
        $sn = $prefix . date('YmdHis') . $suffix;
        if (Db::name($table)->where($field, $sn)->find()) {
            return sn($table, $field, $prefix, $rand_suffix_length, $pool);
        }
        return $sn;
    }
}
if (!function_exists('generate_invite_code')) {
    //生成用户邀请码
    function generate_invite_code($table, $field)
    {

        $letter_all = range('A', 'Z');
        shuffle($letter_all);
        //排除I、O字母
        $letter_array = array_diff($letter_all, ['I', 'O', 'D']);
        //排除1、0
        $num_array = range('2', '9');
        shuffle($num_array);

        $pattern = array_merge($num_array, $letter_array, $num_array);
        shuffle($pattern);
        $pattern = array_values($pattern);

        $code = '';
        for ($i = 0; $i < 6; $i++) {
            $code .= $pattern[mt_rand(0, count($pattern) - 1)];
        }

        $code = strtoupper($code);
        $check = db($table)->where($field, $code)->find();
        if ($check) {
            return generate_invite_code($table, $field);
        }
        return $code;
    }
}
if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @param int    $precision 小数位数
     * @return string
     */
    function format_bytes($size, $delimiter = '', $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $linedata = array_intersect_key($result[$n], $curr);
                    $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 使用短标签打印或返回数组结构
     * @param mixed   $data
     * @param boolean $return 是否返回数据
     * @return string
     */
    function var_export_short($data, $return = true)
    {
        return var_export($data, $return);
        $replaced = [];
        $count = 0;

        //判断是否是对象
        if (is_resource($data) || is_object($data)) {
            return var_export($data, $return);
        }

        //判断是否有特殊的键名
        $specialKey = false;
        array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
            if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
                $specialKey = true;
            }
        });
        if ($specialKey) {
            return var_export($data, $return);
        }
        array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
            if (is_object($value) || is_resource($value)) {
                $replaced[$count] = var_export($value, true);
                $value = "##<{$count}>##";
            } else {
                if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
                    $index = array_search($value, $replaced);
                    if ($index === false) {
                        $replaced[$count] = var_export($value, true);
                        $value = "##<{$count}>##";
                    } else {
                        $value = "##<{$index}>##";
                    }
                }
            }
            $count++;
        });

        $dump = var_export($data, true);

        $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
        $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
        $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
        $dump = preg_replace('#\)$#', "]", $dump); //End

        if ($replaced) {
            $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
                return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
            }, $dump);
        }

        if ($return === true) {
            return $dump;
        } else {
            echo $dump;
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                $response = Response::create('跨域检测无效', 'html', 403);
                throw new HttpResponseException($response);
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                $response = Response::create('', 'html');
                throw new HttpResponseException($response);
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}

if (!function_exists('check_ip_allowed')) {
    /**
     * 检测IP是否允许
     * @param string $ip IP地址
     */
    function check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;
        $forbiddenipArr = config('site.forbiddenip');
        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
        if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
            $response = Response::create('请求无权访问', 'html', 403);
            throw new HttpResponseException($response);
        }
    }
}

if (!function_exists('build_suffix_image')) {
    /**
     * 生成文件后缀图片
     * @param string $suffix 后缀
     * @param null   $background
     * @return string
     */
    function build_suffix_image($suffix, $background = null)
    {
        $suffix = mb_substr(strtoupper($suffix), 0, 4);
        $total = unpack('L', hash('adler32', $suffix, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $background = $background ? $background : "rgb({$r},{$g},{$b})";

        $icon = <<<EOT
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
            <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
            <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
            <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
            <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
            <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
            <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
        </svg>
EOT;
        return $icon;
    }
}


if (!function_exists('api_format_img')) {
    function api_format_img(&$arr)
    {
        if (is_array($arr)) {
            foreach ($arr as $k => $v) {
                if ($v) {

                    if (is_string($v)) {
                        if ((substr($k, strpos($k, 'image')) === 'image' || substr($k, strpos($k, 'images')) === 'images' || substr($k, strpos($k, 'avatar')) === 'avatar' || substr($k, strpos($k, '_url')) === '_url')) {
                            $arr[$k] = add_img_uri($k, $v);
                        }
                    } elseif (is_array($v)) {
                        api_format_img($arr[$k]);
                    } elseif (is_object($v)) {
                        if (method_exists($v, 'toArray')) {
                            $arr[$k] = $v->toArray();
                            api_format_img($arr[$k]);
                        } else {
                            //遍历对象数组
                            foreach ($v as $vk => $vv) {
                                if ((substr($vk, strpos($vk, 'image')) === 'image' || substr($vk, strpos($vk, 'images')) === 'images' || substr($vk, strpos($vk, 'avatar')) === 'avatar' || substr($k, strpos($k, '_url')) === '_url')) {
                                    $v[$vk] = add_img_uri($vk, $vv);
                                }
                            }
                            $arr[$k] = $v;
                        }
                    }
                }
            }
        }
    }
}


if (!function_exists('add_img_uri')) {
    function add_img_uri($k, $v)
    {
        if (substr($k, strpos($k, 'images')) === 'images') {
            $images = explode(',', $v);
            foreach ($images as $ik => $img) {
                if (strpos($img, 'http') !== 0) {
                    $images[$ik] = cdnurl($img, true);
                }
            }
            return implode(',', $images);
        } else {
            if (strpos($v, 'http') !== 0) {
                return  cdnurl($v, true);
            }
        }
        return $v;
    }
}


if (!function_exists('api_mutrl_format_img')) {
    function api_mutrl_format_img($arr, $key)
    {
        // $url = cdnurl();
        foreach ($arr as $k => $v) {


            $tmp = explode(',', $v);
            foreach ($tmp as $g => $img) {
                $tmp[$g] = cdnurl($img, true);
            }
            $arr[$k][$key] = implode(',', $tmp);
        }
        return $arr;
    }
}

if (!function_exists('mkqrcode')) {
    function mkqrcode($code, $path, $name)
    {
        require_once(EXTEND_PATH . '/Helperphpqrcode.php');
        if (!is_dir($path)) {
            var_dump($path);
            @mkdir($path, 0755);
        }
        $save_path = $path . '/' . $name . '.png';
        \Helperphpqrcode::create($code, $save_path);
        return $save_path;
    }
}


/**
 * 输出xml字符
 */
function ToXml($arr = [])
{
    if (!is_array($arr) || count($arr) <= 0) {
        exit("数组数据异常！");
    }

    $xml = "<xml>";
    foreach ($arr as $key => $val) {
        if (is_numeric($val)) {
            $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
        } else {
            $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
    }
    $xml .= "</xml>";
    return $xml;
}
function post_data($url, $param, $type = 'json', $return_array = true, $useCert = [])
{
    $type === false && $type = 'json'; // 兼容老版本
    $type === true && $type = 'file'; // 兼容老版本
    //兼容obj数组
    if ($type == 'json' && (is_array($param) || is_object($param))) {

        $param = json_encode($param, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    } elseif ($type == 'xml' && is_array($param)) {
        $param = ToXml($param);
    }
    // 初始化curl
    $ch = curl_init();
    // 设置超时
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    if (version_compare(phpversion(), '7.0') < 0) {
        if (class_exists('/CURLFile')) { // php5.5跟php5.6中的CURLOPT_SAFE_UPLOAD的默认值不同
            //curl_setopt ( $ch, CURLOPT_SAFE_UPLOAD, true );
        } else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            }
        }
    }

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    // 设置header
    if ($type == 'file') {
        $header[] = "content-type: multipart/form-data; charset=UTF-8";
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    } elseif ($type == 'xml') {
        curl_setopt($ch, CURLOPT_HEADER, false);
    } else {
        $header[] = "content-type: application/json; charset=UTF-8";
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }

    // curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    }
    // curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
    //Helper_Common::curl_redir_exec($ch);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    // 要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // 使用证书：cert 与 key 分别属于两个.pem文件
    if (isset($useCert['certPath']) && isset($useCert['keyPath'])) {
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT, $useCert['certPath']);
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, $useCert['keyPath']);
    }

    $res = curl_exec($ch);

    // 获得响应结果里的：头大小

    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

    // 根据头大小去获取头信息内容

    $pheader = substr($res, 0, $headerSize);
    $flat = curl_errno($ch);
    $msg = '';
    if ($flat) {
        $msg = curl_error($ch);
    }
    curl_close($ch);
    if ($flat) {
        return [
            'curl_erron' => $flat,
            'curl_error' => $msg
        ];
    } else {

        if ($return_array && !empty($res)) {
            $res = $type == 'xml' ? FromXml($res) : json_decode($res, true);
        }

        return $res;
    }
}
/**
 * 将xml转为array
 */
function FromXml($xml)
{
    if (!$xml) {
        exit("xml数据异常！");
    }
    // 将XML转为array
    $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $arr;
}

/**
 * 发送订阅消息
 * @Author   xy
 * @DateTime 2020-02-20T14:41:25+0800
 * @param    [type]                   $acct_id     [description]
 * @param    [type]                   $template_id [description]
 * @param    [type]                   $keywords    [description]
 * @return   [type]                                [description]
 */
function sendSubTemplateMsg($user, $template_id, $keywords, $page = 'pages/index/index')
{

    $app_id = Env::get('wx.appid');
    $app_secret = Env::get('wx.appsecret');
    $access_token = get_wx_token($app_id, $app_secret);
    // $wechat = new Wechat('wxMiniProgram');

    // $access_token = $wechat->getAccessToken();
    if (!$access_token) {
        return [
            'code' => 0,
            'msg' => 'token get err',
        ];
    }



    $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$access_token}";
    //查询form_id
    $key_data = [];

    // foreach ($keywords as $t => $v) {
    //     $key_data["keyword$t"] = array("value" => $v);
    // }

    // for ($i = 0; $i < count($keywords); $i++) {
    //     $t = $i + 1;
    //     $key_data["keyword$t"] = array("value" => $keywords[$i]);
    // }

    $data = array(
        "touser" => $user['openid'],
        "template_id" => $template_id,
        "page" => $page,
        "data" => $keywords
    );

    $res = post_data($url, $data);

    // return $res;

    if ($res['errcode'] == 0) {
        return [
            'code' => 1,
            'msg' => '发送成功',
        ];
    } else {
        return [
            'code' => 0,
            'msg' => $res['errcode'] == 43101 ? '用户未订阅或发送次数用尽' : ($res['errmsg'] ?? '发送失败'),
        ];
    }
}


if (!function_exists('get_wx_token')) {
    function get_wx_token($appid, $appkey)
    {
        $cache_id = 'wx_accesstoken:' . $appid;
        $data = Cache::get($cache_id);

        if ($data !== false && $data) {

            return $data;
        } else {
            //AppSecret(应用密钥)
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appkey;

            $client = new GuzzleHttp\Client();

            $response = $client->get($url);
            $res = $response->getBody();
            $res = json_decode($res, 1);
            if (!empty($res['access_token'])) {
                Cache::set($cache_id, $res['access_token'], 7000);
            }
            return $res['access_token'];
        }
    }
}
